export default class WebMonitorSDK {
  constructor(options = {}) {
    this.options = options;
    this.deviceId = this.initializeDeviceId();
  }

  // 初始化设备ID
  initializeDeviceId() {
    return (
      this.getIDFromStorage() ||
      this.getWindowNameID() ||
      this.generateNewDeviceId()
    );
  }

  // 多级存储查找（新增sessionStorage）
  getIDFromStorage() {
    return (
      this.readStorage('localStorage') ||
      this.readStorage('sessionStorage') ||
      this.readCookie()
    );
  }

  // 统一存储接口
  readStorage(type) {
    try {
      return window[type].getItem('_mon_device_id');
    } catch (e) {
      return null;
    }
  }

  // Cookie读取（带兼容处理）
  readCookie() {
    try {
      const match = document.cookie.match(
        '(^|;)\\s*_mon_device_id\\s*=\\s*([^;]+)'
      );
      return match ? decodeURIComponent(match[2]) : null;
    } catch (e) {
      return null;
    }
  }

  // 使用window.name作为跨会话后备存储
  getWindowNameID() {
    try {
      if (
        window.name &&
        /^mondevid-[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(
          window.name
        )
      ) {
        return window.name.split('mondevid-')[1];
      }
    } catch (e) {}
    return null;
  }

  // 生成新ID（带类型后缀）
  generateNewDeviceId() {
    console.log(this.createUUID(), 'this.createUUID()');
    const deviceId = `${this.createUUID()}-${this.getStorageTypeSuffix()}`;
    this.saveIDToStorage(deviceId);
    this.saveWindowName(deviceId);
    return deviceId;
  }

  // 获取存储类型后缀
  getStorageTypeSuffix() {
    if (this.isStorageAvailable('localStorage')) return 'ls';
    if (this.isStorageAvailable('sessionStorage')) return 'ss';
    if (this.isCookieAvailable()) return 'ck';
    return 'mem';
  }

  // 检测存储可用性
  isStorageAvailable(type) {
    try {
      const storage = window[type];
      storage.setItem('test', 'test');
      storage.removeItem('test');
      return true;
    } catch (e) {
      return false;
    }
  }

  // 检测Cookie可用性
  isCookieAvailable() {
    try {
      document.cookie = 'test=1;SameSite=Lax';
      return document.cookie.indexOf('test=') !== -1;
    } catch (e) {
      return false;
    }
  }

  // 统一保存到所有可用存储
  saveIDToStorage(deviceId) {
    this.saveToStorage('localStorage', deviceId);
    this.saveToStorage('sessionStorage', deviceId);
    this.saveCookie(deviceId);
  }

  // 通用存储保存方法
  saveToStorage(type, deviceId) {
    try {
      window[type].setItem('_mon_device_id', deviceId);
    } catch (e) {}
  }

  // Cookie保存（带特性检测）
  saveCookie(deviceId) {
    try {
      if (!navigator.cookieEnabled) return;

      const date = new Date();
      date.setFullYear(date.getFullYear() + 1);
      document.cookie = `_mon_device_id=${encodeURIComponent(
        deviceId
      )};expires=${date.toUTCString()};path=/;SameSite=Lax`;
    } catch (e) {}
  }

  // 保存到window.name（作为最后后备）
  saveWindowName(deviceId) {
    try {
      window.name = `mondevid-${deviceId}`;
    } catch (e) {}
  }

  // 生成UUID（RFC4122兼容）
  createUUID() {
    const cryptoObj = window.crypto || window.msCrypto;
    if (cryptoObj && cryptoObj.getRandomValues) {
      const buffer = new Uint16Array(8);
      cryptoObj.getRandomValues(buffer);
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
        const r = (buffer[0] + performance.now()) % 16 | 0;
        buffer[0] = r;
        return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16);
      });
    }

    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
      const r = (Math.random() * 16) | 0;
      const v = c === 'x' ? r : (r & 0x3) | 0x8;
      return v.toString(16);
    });
  }

  // 重置设备ID
  resetDeviceId() {
    const newId = this.generateNewDeviceId();
    this.deviceId = newId;
  }
}
